import { login, sysProfile, sysUser } from '@/api/user'
import { getToken, setToken } from '@/utils/auth'
import asyncRoutes from '@/router/modules/index.js'
import router from '@/router'
import { constantRoutes } from '@/router'
import { resetRouter } from '@/router'

const state = {
  // token令牌
  token: getToken() || '',
  // 用户个人信息
  userInfo: ''
}
const mutations = {
  // token 存入
  setToken(state, value) {
    state.token = value
    setToken(value)
  },
  // 个人信息存入
  setUserInfo(state, value) {
    state.userInfo = value
  },
  logout(state) {
    resetRouter()
    state.token = ''
    setToken('')
    state.userInfo = ''
  }
}
const actions = {
  // 登陆调用
  async toLogin(store, value) {
    // login(value)
    //   .then((res) => {
    //     console.log('res', res)
    //     commit('setToken', res.data)
    //   })
    //   .catch((err) => {
    //     console.log('err', err)
    //   })
    const res = await login(value)
    store.commit('setToken', res.data)
    // console.log('res', res)
  },
  async getUserInfo(store) {
    console.log('store', store)
    // 获取用户基本资料 不带头像img
    const res = await sysProfile()
    // 获取员工基本信息 带头像img
    const res2 = await sysUser(res.data.userId)
    // console.log('res2', res2)
    // 通过结构的方法把两个对象合并{...res.data,...res2.data}
    store.commit('setUserInfo', { ...res.data, ...res2.data })
    console.log('个人信息', res, res2)

    const newArr = asyncRoutes.filter((item) => {
      return store.state.userInfo.roles.menus.includes(item.name)
    })
    store.commit('routes/setRouteList', [...constantRoutes, ...newArr], {
      root: true
    })
    newArr.push({ path: '*', redirect: '/404', hidden: true })
    router.addRoutes(newArr)
  }
}
const getters = {}
export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
